package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.BspsMchntBaseInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsMchntBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsUserInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBaseInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsUserInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.MchntBaseInfo;
import cc.rengu.igas.bsps.common.entity.MchntBindInfo;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.BspsUserRoleTypeEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.realize.PublicDealService;
import cc.rengu.igas.bsps.core.realize.impl.PublicDealServiceImpl;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.CashierModifyRequest;
import cc.rengu.igas.bsps.facade.response.CashierModifyResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020/04/01
 */
public class CashierModifyService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        CashierModifyRequest cashierModifyRequest = new CashierModifyRequest();
        ConvertUtil.convertOutput(cashierModifyRequest);
        return cashierModifyRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        CashierModifyRequest cashierModifyRequest = (CashierModifyRequest) request;
        CashierModifyResponse cashierModifyResponse = new CashierModifyResponse();
        BeanUtil.beanCopy(cashierModifyRequest, cashierModifyResponse);
        /*获取参数信息：法人行号、用户标识，商户号，连锁商户号，收银员账号，收银员手机号，收银员姓名，昵称，角色*/
        String instId = cashierModifyRequest.getHeader().getInstId();
        String userId = cashierModifyRequest.getUserId();
        String mchntNo = cashierModifyRequest.getMchntNo();
        String chainMchntNo = cashierModifyRequest.getChainMchntNo();
        String cashierUserId = cashierModifyRequest.getCashierUserId();
        String cashierMobileNo = cashierModifyRequest.getCashierMobileNo();
        String cashierUserName = cashierModifyRequest.getCashierUserName();
        String cashierUserNickName = cashierModifyRequest.getCashierUserNickName();
        String cashierRole = cashierModifyRequest.getCashierRole();
        String transInfoQueryAuth = cashierModifyRequest.getTransInfoQueryAuth();
        String cashierMchntNo = cashierModifyRequest.getCashierMchntNo();

        /*必填性校验*/
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(mchntNo)
                || StringUtil.isEmptyOrNull(cashierUserId) || StringUtil.isEmptyOrNull(cashierUserNickName) || StringUtil.isEmptyOrNull(cashierRole) || StringUtil.isEmptyOrNull(cashierMchntNo)) {
            rglog.error("必填性校验失败！");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /*根据商户号和登录账号查询用户信息*/
        BspsUserInfoMapper bspsUserInfoMapper = new BspsUserInfoMapperImpl();
        UserInfo userInfo = bspsUserInfoMapper.selectBspsUserInfoByUserId(instId, cashierUserId);
        if (null == userInfo) {
            rglog.error("查询收银员信息失败!法人行:<{}>，用户ID:<{}>", instId, cashierUserId);
            throw new BizException(RespCodeEnum.GET_USER_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_INFO_ERROR.getRespDesc());
        }
        /*查询收银员商户绑定信息*/
        BspsMchntBindInfoMapper mchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
        MchntBindInfo mchntBindInfo = mchntBindInfoMapper.selectBspsMchntBindInfoListByUserIdAndMchntNo(instId, cashierUserId, cashierMchntNo);
        if (null == mchntBindInfo) {
            rglog.error("查询收银员绑定商户信息信息失败!法人行:<{}>，用户ID:<{}>，商户号:<{}>", instId, cashierUserId, cashierMchntNo);
            throw new BizException(RespCodeEnum.GET_USER_BIND_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_BIND_INFO_ERROR.getRespDesc());
        }
        /*判断用户是否有权限进行收银员的修改操作*/
        PublicDealService publicDealService = new PublicDealServiceImpl();
        boolean authFlag = publicDealService.checkUserOpAuth(instId, mchntNo, userId, cashierUserId);
        if (!authFlag) {
            rglog.error("用户无权限修改收银员信息");
            throw new BizException(RespCodeEnum.USER_NO_AUTHORITY.getRespCode(), RespCodeEnum.USER_NO_AUTHORITY.getRespDesc());
        }
        /*查询商户信息，判断是否允许修改收银员为店长用*/
        BspsMchntBaseInfoMapper mchntBaseInfoMapper = new BspsMchntBaseInfoMapperImpl();
        MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectBspsMchntBaseInfoByPrimaryKey(instId, mchntNo);
        if (null == mchntBaseInfo || !"01".equals(mchntBaseInfo.getMchntStatus())) {
            rglog.error("查询商户基本信息失败", instId, mchntNo);
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        /*判断修改收银员为店长时，是否为连锁商户门店*/
        if (BspsUserRoleTypeEnum.MCHNT_MANAGER.getRoleType().equals(cashierRole)) {
            if (!"11".equals(mchntBindInfo.getBindMchntType())) {
                rglog.error("商户非连锁商户门店，不能新增店长！");
                throw new BizException(RespCodeEnum.MCHNT_TYPE_ERROR.getRespCode(), "店长所属商户非连锁商户门店，无权新增店长");
            } else {
                List<MchntBindInfo> mchntBindInfoList = mchntBindInfoMapper.selectBspsMchntBindInfoByMchntNoAndRoleType(instId, cashierMchntNo, "01");
                if (mchntBindInfoList != null) {
                    if (mchntBindInfoList.size() != 1) {
                        throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), "门店店长存在多个");
                    } else {
                        String bindUserId = mchntBindInfoList.get(0).getBindUserId();
                        if (!mchntBindInfo.getBindUserId().equals(bindUserId)) {
                            throw new BizException(RespCodeEnum.MCHNT_MANAGER_EXIST_ERROR.getRespCode(), "门店店长已存在");
                        }
                    }
                }
            }
        }

        /* 开启数据库事务 */
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.OLTP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        int iReturnCode;
        /*1-用户信息更新*/
        /*手机号更新*/
        if (!StringUtil.isEmptyOrNull(cashierMobileNo)) {
            userInfo.setMobileNo(cashierMobileNo);
        }
        /*收银员名称更新*/
        if (!StringUtil.isEmptyOrNull(cashierUserName)) {
            userInfo.setUserName(cashierUserName);
        }
        /*收银员昵称更新*/
        if (!StringUtil.isEmptyOrNull(cashierUserNickName)) {
            userInfo.setNickName(cashierUserNickName);
        }
        userInfo.setLastOprId(userId);
        userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        /*更新用户信息*/
        iReturnCode = bspsUserInfoMapper.updateBspsUserInfoByPrimaryKey(userInfo);
        if (0 != iReturnCode) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("更新用户信息表失败,iReturnCode:<{}>", iReturnCode);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        /*2-更新用户与商户绑定信息*/
        /*连锁商户号赋值*/
        if (!StringUtil.isEmptyOrNull(chainMchntNo)) {
            mchntBindInfo.setChainMchntNo(chainMchntNo);
        }
        /**判断是否有权限调整查询权限*/
        if (!StringUtil.isEmptyOrNull(transInfoQueryAuth)) {
            boolean transInfoQueryAuthFlag = publicDealService.checkUserOpAuthTransInfoQuery(instId, mchntNo, userId, cashierUserId);
            if (!transInfoQueryAuthFlag) {
                rglog.error("用户无权限操作该收银员");
                throw new BizException(RespCodeEnum.USER_NO_AUTHORITY.getRespCode(), RespCodeEnum.USER_NO_AUTHORITY.getRespDesc());
            }
            String remark1 = mchntBindInfo.getRemark1();
            if (!StringUtil.isEmptyOrNull(remark1)) {
                try {
                    Map<String, Object> reqMap = JSONObject.parseObject(remark1);
                    if (transInfoQueryAuth != null && transInfoQueryAuth.equals("01")) { //设置了查询订单权限
                        reqMap.put("adminAuth", "Y");
                    } else {
                        reqMap.put("adminAuth", "N");
                    }
                    mchntBindInfo.setRemark1(JSONObject.toJSONString(reqMap));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Map<String, Object> reqMap = new HashMap<>();
                if (transInfoQueryAuth != null && transInfoQueryAuth.equals("01")) { //设置了查询订单权限
                    reqMap.put("adminAuth", "Y");
                } else {
                    reqMap.put("adminAuth", "N");
                }
                mchntBindInfo.setRemark1(JSONObject.toJSONString(reqMap));
            }
        }

        mchntBindInfo.setMchntNo(cashierMchntNo);
        mchntBindInfo.setBindUserRole(cashierRole);
        mchntBindInfo.setBindNickName(cashierUserNickName);
        mchntBindInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        mchntBindInfo.setLastOprId(userId);
        iReturnCode = mchntBindInfoMapper.updateBspsMchntBindInfo(mchntBindInfo);
        if (0 != iReturnCode) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("更新商户绑定信息表失败,iReturnCode:<{}>", iReturnCode);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        dbsUtil.dbsEndTransaction(true);

        /* 拼装响应结果 */
        BizResponse<CashierModifyResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(cashierModifyResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        CashierModifyResponse cashierModifyResponse = (CashierModifyResponse) bizResponse.getResult();
        ConvertUtil.convertInput(cashierModifyResponse);
    }
}
